<?php

namespace Payment;

use Payment\Charge\Fu\FuClose;
use Payment\Charge\LTF\LTFClose;
use Payment\Charge\Sw\SwClose;
use Payment\Charge\SwThree\SwThreeClose;
use Payment\Charge\YS\YSClose;
use Payment\Common\BaseStrategy;
use Payment\Common\PayException;

/**
 * Class CloseContext
 *
 * @package Payment
 */
class CloseContext{

	/**
	 * 关闭订单的渠道
	 *
	 * @var BaseStrategy
	 */
	protected $closeHandler;

	/**
	 * 设置对应的关闭订单渠道
	 *
	 * @param string $channel 关闭订单渠道
	 *  - @param array $config 配置文件
	 * @throws PayException
	 * @see Config
	 * @author yeran
	 */
	public function initCloseHandler($channel, array $config){
		try{
			switch($channel){
				case Config::SW_CHARGE:
					$this->closeHandler = new SwClose($config);
					break;
                case Config::SW_T_CHARGE:
                    $this->closeHandler = new SwThreeClose($config);
                    break;
				case Config::FU_CHARGE:
					$this->closeHandler = new FuClose($config);
					break;
				case Config::LTF_CHARGE:
					$this->closeHandler = new LTFClose($config);
					break;
                case Config::YS_CHARGE:     //易生支付
                    $this->closeHandler = new YSClose($config);
                    break;
				default:
					throw new PayException('当前仅支持：SW_CHARGE、FU_CHARGE、LTF_CHARGE');
			}
		}catch(PayException $e){
			throw $e;
		}
	}

	/**
	 * 通过环境类调用交易关闭操作
	 *
	 * @param array $data
	 * @return array
	 * @throws PayException
	 * @author yeran
	 */
	public function close(array $data){
		if(!$this->closeHandler instanceof BaseStrategy){
			throw new PayException('请检查初始化是否正确');
		}

		try{
			return $this->closeHandler->handle($data);
		}catch(PayException $e){
			throw $e;
		}
	}
}
